package com.zhu.salesmanagement.network;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zhu.salesmanagement.R;
import com.zhu.salesmanagement.StoreInfoActivity;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.utils.Util;

import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class PostData {

    public static byte[] mImage = null;

    /**
     * 获取新增门店数据
     * @param eid 业务员ID
     * @param uuid 权限ID
     * @param context 上下文
     * @param propertyList 属性列表
     */
    public static Object[] getNewAddStores(String eid, String uuid, Context context, List<Object> propertyList){
        List<Object> list = new ArrayList<Object>();
        Cursor cursor = null;
        try{
            cursor = context.getContentResolver().query(
                    SalesSettings.MyAddStoresColumns.CONTENT_URI, null, null, null, null);
            final int nameIndex = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.NAME);
            final int addressIndex = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.ADDRESS);
            final int contactIndex = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.CONTACT);
            final int mobileIndex = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.MOBILE);
            final int photoIndex = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.PHOTO);
            final int latIndex = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.LAT);
            final int lngIndex = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.LNG);
            final int typeIndex = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.TYPE);

            final int sp1Index = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.SP1);
            final int sp2Index = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.SP2);
            final int sp3Index = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.SP3);
            final int sp4Index = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.SP4);
            final int sp5Index = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.SP5);
            final int sp6Index = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.SP6);
            final int sp7Index = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.SP7);
            final int sp8Index = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.SP8);
            final int sp9Index = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.SP9);
            final int sp10Index = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.SP10);
            final int sp11Index = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.SP11);
            final int sp12Index = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.SP12);
            final int sp13Index = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.SP13);
            final int sp14Index = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.SP14);
            final int cidIndex = cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.STOREID);

            while (cursor.moveToNext()) {
                Map map = new HashMap<String, Object>();
                String cid = cursor.getString(cidIndex);

                map.put("sStoreProperty1", getStringValue(cursor,sp1Index));
                map.put("decStoreProperty2", Double.parseDouble(getValue(cursor, sp2Index)));
                map.put("iStoreProperty3", Integer.parseInt(getValue(cursor, sp3Index)));
                map.put("iStoreProperty4", Integer.parseInt(getValue(cursor, sp4Index)));
                map.put("decStoreProperty5", Double.parseDouble(getValue(cursor, sp5Index)));
                map.put("decStoreProperty6", Double.parseDouble(getValue(cursor, sp6Index)));

                map.put("iStoreProperty7", cursor.getInt(sp7Index));
                map.put("iStoreProperty8", cursor.getInt(sp8Index));
                map.put("iStoreProperty9", cursor.getInt(sp9Index));
                map.put("iStoreProperty10",cursor.getInt(sp10Index));
                map.put("iStoreProperty11", cursor.getInt(sp11Index));
                map.put("iStoreProperty12", cursor.getInt(sp12Index));
                map.put("iStoreProperty13", cursor.getInt(sp13Index));

                map.put("sStoreProperty14", getStringValue(cursor,sp14Index));

                if(cid == null || cid.trim().length() == 0){
                    map.put("sCustomerName", cursor.getString(nameIndex));
                    map.put("sCustomerAddress", cursor.getString(addressIndex));
                    map.put("sCustomerContractor", cursor.getString(contactIndex));
                    map.put("sTel", cursor.getString(mobileIndex));
                    map.put("sDealtEmployeeID", eid);
                    //map.put("iVisitCategory", Integer.parseInt(cursor.getString(typeIndex)));
                    map.put("sStoreCategory", "");
                    map.put("decLongitude", Double.parseDouble(cursor.getString(lngIndex)));
                    map.put("decLatitude", Double.parseDouble(cursor.getString(latIndex)));
                    byte[] photo = cursor.getBlob(photoIndex);
                    if(Actions.DEBUG){
                    	Log.e("zhu","photo="+photo.length);
                    }
                    map.put("imgPhoto", /*getImage(context)*/photo);
                    list.add(map);
                    //map.put("imgPhoto", cursor.getBlob(photoIndex));
                }else{
                    map.put("sInquireDate", cursor.getString(nameIndex));
                    map.put("sCustomerID", cid);
                    map.put("sInquireEmployeeID", eid);
                    propertyList.add(map);
                }
            }
        }catch(Exception e){
        	e.printStackTrace();
            if(Actions.DEBUG){
            	Log.e("zhu","getNewAddStores error");
            }
        }finally{
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
        }
        if(list.size() > 0){
        	return new Object[]{ eid, uuid, list };
        }else{
        	return null;
        }
    }

    private static String getValue(Cursor cursor, int index){ 
    	String value = cursor.getString(index);
    	if(value == null || value.trim().length() == 0){
    		value = "0";
    	}
    	return value;
    }

    private static String getStringValue(Cursor cursor, int index){ 
    	String value = cursor.getString(index);
    	if(value == null){
    		value = "";
    	}
    	return value;
    }

    /**
     * 删除新增门店数据
     * @param context 上下文
     */
    public static void deleteAllNewAddedStores(Context context){
        if(!Util.isEndVisit(context)){
            String where = SalesSettings.MyAddStoresColumns.TYPE +" = \'" + StoreInfoActivity.TYPE_NEWSTORE +"\'";
            context.getContentResolver().delete(SalesSettings.MyAddStoresColumns.CONTENT_URI_NO_NOTIFICATION, where, null);
        }else{
            context.getContentResolver().delete(SalesSettings.MyAddStoresColumns.CONTENT_URI_NO_NOTIFICATION, null, null);
        }
    }

    /**
     * 删除门店照片
     */
    public static void deleteStorePhotos(Context context){
        context.getContentResolver().delete(SalesSettings.StorePhotosColumns.CONTENT_URI_NO_NOTIFICATION, null, null);
    }

    /**
     * 获取歇业门店数据
     * @param eid 业务员ID
     * @param uuid 权限ID
     * @param context 上下文
     */
    public static Object[] getCustomerClosedList(String eid, String uuid, Context context){
    	 List<String> list = new ArrayList<String>();
    	Cursor cursor = null;
        try{
            cursor = context.getContentResolver().query(
                    SalesSettings.VisitedStoresColumns.CONTENT_URI, null, "close = 1", null, null);
            final int cidIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.STOREID);
            while (cursor.moveToNext()) {
            	list.add(cursor.getString(cidIndex));
            }
        }catch(Exception e){
        	e.printStackTrace();
            if(Actions.DEBUG){
            	Log.e("zhu","getNewAddStores error");
            }
        }finally{
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
        }
        if(Actions.DEBUG){
        	Log.e("zhu","getCustomerClosedListSize=" + list.size());
        }
        if(list.size() > 0){
        	return new Object[]{ eid, uuid, list };
        }else{
        	return null;
        }
    }

    /**
     * 删除提醒数据
     * @param context 上下文
     */
    public static void deleteAllRemindsData(Context context){
    	String where = "";
    	Cursor cursor = null;
    	String whereId = "";
        try{
            cursor = context.getContentResolver().query(
                    SalesSettings.RemindsColumns.CONTENT_URI, new String[]{ SalesSettings.RemindsColumns._ID, SalesSettings.RemindsColumns.EVENTID, SalesSettings.RemindsColumns.DEADTIME }, null, null, null);
            final int eventIdIndex = cursor.getColumnIndexOrThrow(SalesSettings.RemindsColumns.EVENTID);
            final int idIndex = cursor.getColumnIndexOrThrow(SalesSettings.RemindsColumns._ID);
            final int deadtimeIndex = cursor.getColumnIndexOrThrow(SalesSettings.RemindsColumns.DEADTIME);
            while (cursor.moveToNext()) {
                String sdeadtime = cursor.getString(deadtimeIndex);
                if(sdeadtime == null || sdeadtime.trim().length() == 0){
                    sdeadtime = "0";
                }
                long deadtime = Long.parseLong(sdeadtime);
                if(System.currentTimeMillis() >= deadtime){
                    String eid = cursor.getString(eventIdIndex);
                    long id = cursor.getLong(idIndex);
                    if(eid != null && eid.length() > 0){
                        if (where.length() == 0) {
                            where += SalesSettings.RemindsColumns._ID + " = " + eid;
                        } else {
                            where += " or " + SalesSettings.RemindsColumns._ID + " = " + eid;
                        }
                    }
                    if(whereId.length() == 0){
                        whereId = SalesSettings.RemindsColumns._ID +"=" + id;
                    }else{
                        whereId += " or " + SalesSettings.RemindsColumns._ID + " = " + id;
                    }
                }
            }
        }catch(Exception e){
        	e.printStackTrace();
            if(Actions.DEBUG){
            	Log.e("zhu","getNewAddStores error");
            }
        }finally{
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
        }
        if(whereId.length() > 0){
            if(Actions.DEBUG){
                Log.e("zhu","whereId="+whereId);
            }
            context.getContentResolver().delete(SalesSettings.RemindsColumns.CONTENT_URI_NO_NOTIFICATION, whereId, null);
        }

        if(where.length() > 0){
        	if(Actions.DEBUG){
        		Log.e("zhu","where="+where);
        	}
        	Actions.deleteEvent(context, where);	
        }
    }

    /**
     * 获取门店照片数据
     * @param eid 业务员ID
     * @param uuid 权限ID
     * @param context 上下文
     */
    public static List<Object> getStorePhotos(String eid, String uuid, Context context){
        List<Object> list = new ArrayList<Object>();
        Cursor cursor = null;
        try{
            cursor = context.getContentResolver().query(SalesSettings.StorePhotosColumns.CONTENT_URI, null, null, null, null);
            final int dataIndex = cursor.getColumnIndexOrThrow(SalesSettings.StorePhotosColumns.DATA);
            final int dtaidIndex = cursor.getColumnIndexOrThrow(SalesSettings.StorePhotosColumns.DTASKACTUALID);
            final int cidIndex = cursor.getColumnIndexOrThrow(SalesSettings.StorePhotosColumns.STOREID);
            final int photosourceIndex = cursor.getColumnIndexOrThrow(SalesSettings.StorePhotosColumns.PHOTOSOURCE);
            final int lngIndex = cursor.getColumnIndexOrThrow(SalesSettings.StorePhotosColumns.PHOTO_LNG);
            final int latIndex = cursor.getColumnIndexOrThrow(SalesSettings.StorePhotosColumns.PHONO_LAT);
            final int timeIndex = cursor.getColumnIndexOrThrow(SalesSettings.StorePhotosColumns.PHONO_TAKETIME);

            while (cursor.moveToNext()) {
                Map map = new HashMap<String, Object>();
                //String cid = cursor.getString(cidIndex);
                String photosource = cursor.getString(photosourceIndex);
                if(photosource == null || photosource.equals("default")){
                    photosource = "";
                }
                if(Actions.DEBUG){
                    Log.e("zhu", cursor.getString(lngIndex) + "," + cursor.getString(latIndex) +"," + cursor.getString(timeIndex));
                }
                map.put("sPhotoSource", "CRC");
                map.put("sDatingTaskActualID", cursor.getString(dtaidIndex));
                map.put("imgPhoto", cursor.getBlob(dataIndex));
                map.put("sDataCategoryID", photosource);
                map.put("decPhotoLongitude", Double.parseDouble(cursor.getString(lngIndex)));
                map.put("decPhotoLatitude", Double.parseDouble(cursor.getString(latIndex)));
                map.put("dShootDate", new Date(Long.parseLong(cursor.getString(timeIndex))));
                list.add(map);
            }
        }catch(Exception e){
            e.printStackTrace();
            if(Actions.DEBUG){
                Log.e("zhu","getStorePhotos error");
            }
        }finally{
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
        }
        return list;
    }

    public static byte[] getImage(Context context){
        if(mImage == null){
            Resources res = context.getResources();
            Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.temp);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
            if(bmp != null){
                bmp.recycle();
            }
            mImage = baos.toByteArray();
        }
        return mImage;
    }
//    public static Object[] getVistedTaskList(String eid, String uuid, Context context){
//    	List<Object> list = new ArrayList<Object>();
//    	Cursor cursor = null;
//    	 try{
//             cursor = context.getContentResolver().query(SalesSettings.VisitedStoresColumns.CONTENT_URI, null, "visit = 1", null, null);
//             final int idIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns._ID);
//             final int storeidIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.STOREID);
//             final int itemnoIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.ITEMNO);
//             final int checkintimeIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKIN_TIME);
//             final int checkouttimeIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKOUT_TIME);
//             final int visitedIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.VISITSTATUS);
//             final int taskidIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.TASKID);
//             final int taskdateIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.TASTDATE);
//             final int aeidIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.AEMPLOYEEID);
//             final int checkinLatIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKIN_LAT);
//             final int checkinLngIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKIN_LNG);
//             final int checkoutLatIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKOUT_LAT);
//             final int checkoutLngIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKOUT_LNG);
//
//             while (cursor.moveToNext()) {
//                 Map map = new HashMap<String, Object>();
//                 map.put("dActualDate", new Date(Long.parseLong(cursor.getString(taskdateIndex))));
//                 map.put("dSignInTime", new Date(Long.parseLong(cursor.getString(checkintimeIndex))));
//                 map.put("decSignInLongitude", Double.parseDouble(cursor.getString(checkinLngIndex)));
//                 map.put("decSignInLatitude", Double.parseDouble(cursor.getString(checkinLatIndex)));
//                 map.put("dSignOutTime", new Date(Long.parseLong(cursor.getString(checkouttimeIndex))));
//                 map.put("decSignOutLongitude", Double.parseDouble(cursor.getString(checkoutLngIndex)));
//                 map.put("decSignOutLatitude", Double.parseDouble(cursor.getString(checkoutLatIndex)));
//                 map.put("sVisitEmployeeID", cursor.getString(aeidIndex));
//                 map.put("sCustomerID", cursor.getString(storeidIndex));
//                 map.put("sDatingTaskID", cursor.getString(taskidIndex));
//                 list.add(map);
//             }
//         }catch(Exception e){
//         	e.printStackTrace();
//             if(Actions.DEBUG){
//             	Log.e("zhu","getVistedTaskList error");
//             }
//         }finally{
//             if(cursor != null){
//                 cursor.close();
//                 cursor = null;
//             }
//         }
//         if(list.size() > 0){
//         	return new Object[]{ eid, uuid, list };
//         }else{
//         	return null;
//         }
//    }
//
//    public static void deleteVistedTaskList(Context context){
//    	context.getContentResolver().delete(SalesSettings.VisitedStoresColumns.CONTENT_URI, "visit = 1", null);
//    }
}
